<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>RFE map</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/tundra/tundra.css" />

<style type="text/css"><!--
.tinyHeaderClass {font-size:50%;}
.formQuestion {
	background-color:#d0e3f5;
	padding:0.3em;
	font-weight:900;
	font-family:Verdana, Arial, sans-serif;
	font-size:0.8em;
	color:#5a5a5a;
}
.formAnswer {
	background-color:#f5eede;
	padding:0.3em;
	margin-bottom:1em;
	width: 100%;
}
.pageSubContentTitle {
		color:#8e8e8e;
		font-size:1em;
		font-family:Verdana, Arial, sans-serif;
		margin-bottom:0.75em;
}
body .short {
	width: 3em;
}
body .medium {
	width: 10em;
}
body .long {
	width: 20em;
}
.firstLabel {
	display: inline-block;
	display: -moz-inline-box;
	width: 10em;
	min-width: 10em;
}
.secondLabel {
	width: auto;
	margin-left: 5em;
	margin-right: 1em;
}
fieldset label {
	margin-right: 1em;
}
.noticeMessage {
	display: block;
	float: right;
	font-weight: normal;
	font-family:Arial, Verdana, sans-serif;
	color:#663;
	font-size:0.9em;
}
/* grid.css */
.container {width:950px;margin:0 auto;}
.showgrid {background:url(src/grid.png);}
.column, .span-1, .span-2, .span-3, .span-4, .span-5, .span-6, .span-7, .span-8, .span-9, .span-10, .span-11, .span-12, .span-13, .span-14, .span-15, .span-16, .span-17, .span-18, .span-19, .span-20, .span-21, .span-22, .span-23, .span-24 {float:left;margin-right:10px;}
.last {margin-right:0;}
.span-1 {width:30px;}
.span-2 {width:70px;}
.span-3 {width:110px;}
.span-4 {width:150px;}
.span-5 {width:190px;}
.span-6 {width:230px;}
.span-7 {width:270px;}
.span-8 {width:310px;}
.span-9 {width:350px;}
.span-10 {width:390px;}
.span-11 {width:430px;}
.span-12 {width:470px;}
.span-13 {width:510px;}
.span-14 {width:550px;}
.span-15 {width:590px;}
.span-16 {width:630px;}
.span-17 {width:670px;}
.span-18 {width:710px;}
.span-19 {width:750px;}
.span-20 {width:790px;}
.span-21 {width:830px;}
.span-22 {width:870px;}
.span-23 {width:910px;}
.span-24 {width:950px;margin-right:0;}
--></style>

<!--[if IE]>
  <script src="http://danvk.org/dygraphs/excanvas.js"></script>
<![endif]-->
<script src="http://danvk.org/dygraphs/dygraph-combined.js"></script> 

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
</script>
<script type="text/javascript">
	djConfig = { parseOnLoad:true, isDebug:false };
</script>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load('dojo', '1.5');  
  google.load('visualization', '1', {packages:['table']});
</script>
<script src="proj4js-combined.js"></script> 
<script src="settings.js"></script> 
<script type="text/javascript">
  dojo.require('dojo.parser');
  dojo.require('dojo.io.script');
  dojo.require('dijit.form.Form');
  dojo.require('dijit.form.RadioButton');
  dojo.require('dijit.form.Button');
  dojo.require('dijit.form.Select');
  dojo.require('dijit.form.ValidationTextBox');
  dojo.require('dijit.form.TextBox');
  dojo.require('dijit.form.NumberTextBox');
  dojo.require('dijit.form.FilteringSelect');

  dojo.addOnLoad(setup);

  Proj4js.reportError = function(msg) {alert(msg);}
  
  // Brand colours
  var bcols = {green:"#CCFF33",blue:"#031F73",cyan:"#00ADD0", olive:"#878800"};

  var last_latlng;
  var outDiv;
  var map;
  var circle;
  var markers = [];
  var graphData = [];
  var srcProj;
  var dstProj;
  var graphhi, graphlo;  // The Dygraphs
  var overlay;  // The image overlay

function ImageOverlay(bounds, image, map) {
  this.bounds_ = bounds;
  this.image_ = image;
  this.map_ = map;
  this.div_ = null;
  this.setMap(map);
}

ImageOverlay.prototype = new google.maps.OverlayView();

ImageOverlay.prototype.onAdd = function() {
  var div = document.createElement('DIV');
  div.style.border = "none";
  div.style.borderWidth = "0px";
  div.style.position = "absolute";

  var img = document.createElement("img");
  img.src = this.image_;
  img.style.width = "100%";
  img.style.height = "100%";
  div.appendChild(img);
  this.div_ = div;
  var panes = this.getPanes();
  panes.overlayLayer.appendChild(div);
}

ImageOverlay.prototype.draw = function() {
  var overlayProjection = this.getProjection();
  var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
  var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());
  var div = this.div_;
  div.style.left = sw.x + 'px';
  div.style.top = ne.y + 'px';
  div.style.width = (ne.x - sw.x) + 'px';
  div.style.height = (sw.y - ne.y) + 'px';
}

ImageOverlay.prototype.onRemove = function() {
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
}

  function initialise() {
     Proj4js.defs["AFRRFE"] = "+proj=aea +lat_1=-19 +lat_2=21 +lat_0=1 +lon_0=20 +x_0=0 +y_0=0 +units=m +ellps=clrk66 +to_meter=8000 +no_defs";
    Proj4js.defs["LONGLAT"] = "+proj=longlat +ellps=intl +towgs84=-637,-549,-203,0,0,0,0, +no_defs";
    srcProj = new Proj4js.Proj('LONGLAT');    //source coordinates will be in Longitude/Latitude
    rfeProj = new Proj4js.Proj('AFRRFE');     //destination coordinates

    outDiv = dojo.byId("out_div");
    var myOptions = {
      zoom: 7,
      center: new google.maps.LatLng(settings.centre.lat, settings.centre.lon),
      mapTypeControl: false, 
      mapTypeId: google.maps.MapTypeId.TERRAIN,
      streetViewControl: false
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    //google.maps.event.addListener(map, 'zoom_changed', function() {
    //  alert("zoom");
    // });
    google.maps.event.addListener(map, 'click', function(event) {
      fetchDataByPosn(event.latLng);
    }); 

   var wxMapOptions = {
    map: map,
    name: "Wx",
    minZoom: 3,
    maxZoom: 10
   }

  var wxMapType =  new google.maps.StyledMapType(wxstyle,wxMapOptions);
  
  map.mapTypes.set('wx', wxMapType);
  map.setMapTypeId('wx');

  // Load CLIMAT stations
  fusionQuery('SELECT id, name, location FROM 522056',stationMarkers);

  return 0;
  }


 function drawCircle(latlng){
   if(circle){circle.setMap(null)};
   circle = new google.maps.Circle({center:latlng,radius:10000,
		strokeColor:bcols.cyan,strokeOpacity:1,strokeWeight:2,
                fillColor:bcols.cyan,fillOpacity:0.5});
   circle.setMap(map);
   //google.maps.event.addListener(circle, 'click', function(event) {
   //   do_something(event.latLng);
   // }); 
   return 0;
 }

function ARFEll(p){
     p.x -= (4237357/8000);
     p.y = (4272328/8000) - p.y;
     Proj4js.transform(rfeProj, srcProj, p);
     return p;
}

function ARFExy(p){
     Proj4js.transform(srcProj, rfeProj, p);
     p.x += (4237357/8000);
     p.y = (4272328/8000) - p.y;
     return p;
}

function ARFEpercent(p){
     Proj4js.transform(srcProj, rfeProj, p);
     p.x += (4237357/8000);
     p.y = (4272328/8000) - p.y;
     p.x = p.x / 994;
     p.y = p.y / 1089;
     return p;
}

var selected_date;

function graphHighlightCb(canvas, area, g) {
              var posn = g.toDomCoords(selected_date, 0);
              var left = posn[0]-1;
              var right = posn[0]+2;
              canvas.fillStyle = "rgba(204, 255, 51, 1.0)";
              canvas.fillRect(left, area.y, right - left, area.h);
            };

function plotGraph(retdata){
  hiGraph(retdata);
}

function stationGraph( resp ){
  var data = resp.table.rows;
  var dekrain = new Array();
  for(var i in data){
    var e = data[i][0].split("-");
    dekrain[e[1]-1] = Number(data[i][1])/3;
  }
  var settings =  {labels:['date','dekad rain','station'],customBars:true,errorBars:true};
  for(var i in graphData){
     mnth =  graphData[i][0].getMonth();
     graphData[i][2] = new Array();
     rain = dekrain[mnth];
     graphData[i][2][0] = rain;
     graphData[i][2][1] = rain;
     graphData[i][2][2] = rain;
  } 
  graphhi = new Dygraph(document.getElementById("graphdivhi"), graphData, settings);
  return 0;
}

function hiGraph(retdata){
  var vals = dijit.byId('rainForm').getValues();
  var period = vals.period;
  var settings;
  
  if(period == 'dekad'){
    graphData = retdata.dekadrain;
    settings =  {labels:['date','dekad rain'],customBars:true,errorBars:true};
  }
  else{
    graphData = retdata.monthrain;
    settings =  {labels:['date','month rain']};
  }

  for(var i in graphData){
     var d = new Date();
     var e = graphData[i][0].split("-");
     d.setFullYear(e[0]); d.setMonth(e[1]-1);d.setDate(e[2]);
     graphData[i][0] = d;
  } 
  settings.clickCallback =  function(e, x, pts) {
                selected_date = new Date(x);
                graphhi.updateOptions( { 'underlayCallback': graphHighlightCb } );
                addOverlay(new Date(x), last_latlng);
              };

  graphhi = new Dygraph(document.getElementById("graphdivhi"), graphData,settings);  
  // Or keep graph and update using -
  //graphhi.updateOptions( { 'file': graphData } );
  
  dojo.byId("info").innerHTML = retdata.message;
  return 0;
}

function addOverlay(date, posn){
    var swBound = new google.maps.LatLng(posn.lat()-2, posn.lng()-2);
    var neBound = new google.maps.LatLng(posn.lat()+2, posn.lng()+2);
    var bounds = new google.maps.LatLngBounds(swBound, neBound);

    var topLeft = ARFEpercent({y:neBound.lat(),x:swBound.lng()});
    var bottomRight = ARFEpercent({y:swBound.lat(),x:neBound.lng()});

    var dek = Math.floor(date.getDate()/10) + 1; 
    var args = {
      dek:dek,mon:date.getMonth()+1,year:date.getFullYear(),
      left:topLeft.x,top:topLeft.y,right:bottomRight.x,bottom:bottomRight.y
    };
 
    var query = dojo.objectToQuery(args);
    //var tile = '/arfeimg?' + query;
    var tile = 'http://map.wepoco.com/arfeimg?' + query;
    if(overlay){overlay.setMap(null)};
    overlay = new ImageOverlay(bounds, tile, map);
}

function unzoom(){
  graphhi.updateOptions({dateWindow: null,valueRange: null});
  graphlo.updateOptions({dateWindow: null,valueRange: null});
  return 0;
}  

// If settings are changed, e.g. year or daily,dekad,month then we need to
// re-plot for the last map position selected.  
function fetchData(){
  return fetchDataByPosn(last_latlng);
}

function temperatureGraph( resp ){
  var temData = resp.table.rows;
  var settings =  {labels:['date','mean C', 'min C', 'max C']};

  for(var i in temData){
     var d = new Date();
     var e = temData[i][0].split("-");
     d.setFullYear(e[0]); d.setMonth(e[1]-1);d.setDate(e[2]);
     temData[i][0] = d;
  } 

  graphlo = new Dygraph(document.getElementById("graphdivlo"), temData,settings);  
}



// Map click listener
function fetchDataByPosn(latlng) {

     last_latlng = latlng;
     document.getElementById("graphdivhi").innerHTML="";
     document.getElementById("graphdivlo").innerHTML="";
     mylatlng = latlng;
     drawCircle(latlng);
     dijit.byId('locationForm').set('value',{lat:latlng.lat(),lng:latlng.lng()});
     var p;
     var vals = dijit.byId('rainForm').getValues();
     var year = vals['year'];

     var text = "";
     /*
     p = ARFEll({x:0,y:0});
     text += "<br> hdr top left lng:" + p.x + " lat:" + p.y;
     p = ARFEll({x:994,y:1089});
     text += "<br> hdr top left lng:" + p.x + " lat:" + p.y;
     dojo.byId("info").innerHTML = text;
     */
     p = ARFExy({y:latlng.lat(),x:latlng.lng()});

     /*
     // Can use xhrGet when this page served from map.wepoco.com
     // Otherwise must use jsonp call.
     var xhrArgs = {
        url:"arfe", content:{x:p.x,y:p.y,year:year,dekad:1,count:36},handleAs:"json",
        load: function(data) {plotGraph(data);},
        error: function(error) {alert("Error " + error);}};
     var deferred = dojo.xhrGet(xhrArgs);
     */

     // See http://docs.dojocampus.org/dojo/io/script
     var jsonpArgs = {
        //Cross domain works - use this URL 
        url: "http://map.wepoco.com/arfe",content:{x:p.x,y:p.y,year:year,dekad:1,count:36},  
        callbackParamName: "callback",
        load: function(data) {plotGraph(data);return 0;},
        error: function(error) {alert("Error " + error);return 0;}};
     dojo.io.script.get(jsonpArgs);

     var lat = latlng.lat();
     var lng = latlng.lng();
     //var latc = ((lat/2) - ((lat/2)%1))*2;
     //var lngc = ((lng/2) - ((lng/2)%1))*2;
     fusionQuery("SELECT locn_id, location FROM 748569 ORDER BY ST_DISTANCE(location,LATLNG("+lat+","+lng+")) LIMIT 1",
       get_locn);

     return 0;
  }

function showme( resp ){
  alert("check the console");
  console.dir(resp);
  return 0;
}

function get_locn( resp ){
  var data = resp.table.rows; 
  if(data.length == 0){
    return null;
  }
  var locn = data[0][0];
  var vals = dijit.byId('rainForm').getValues();
  var year = vals['year'];
  fusionQuery("SELECT date, air, tmin, tmax FROM 748569 WHERE locn_id LIKE '" + locn + "' " +  
  "AND date STARTS WITH '" + year + "' " + "LIMIT 12", temperatureGraph);
}

function stationGraph( resp ){
  var data = resp.table.rows; 
  if(data.length == 0){
    // no data for this station,year
    return 0;
  }
  var dekrain = new Array();
  for(var i in data){
    var e = data[i][0].split("-");
    dekrain[e[1]-1] = Number(data[i][1])/3;
  }
  var settings =  {labels:['date','dekad rain','station'],customBars:true,errorBars:true};
  for(var i in graphData){
     mnth =  graphData[i][0].getMonth();
     graphData[i][2] = new Array();
     rain = dekrain[mnth];
     graphData[i][2][0] = rain;
     graphData[i][2][1] = rain;
     graphData[i][2][2] = rain;
  } 
  graph = new Dygraph(document.getElementById("graphdivhi"), graphData, settings);
  return 0;
}

function stationMarkers( data ){
  var rows = data.table.rows;
  for(var i in rows){
    var latlng = rows[i][2].split(',');
    var posn = new google.maps.LatLng(latlng[0],latlng[1]);
    var marker = new google.maps.Marker({
            map: map,
            title: rows[i][0] + " " + rows[i][1],
	    wmo: rows[i][0], // WMO station ID and date used as index in rainfall table 
            position: posn
        });
    google.maps.event.addListener(marker, 'click', function() {
	 var vals = dijit.byId('rainForm').getValues();
	 var year = vals['year'];
         if(graphData.length == 0){ fetchDataByPosn(this.position); }
         fusionQuery("SELECT date, rain FROM 522347 WHERE date STARTS WITH '"+year+"' AND id="+this.wmo,stationGraph);
        });
    markers.push(marker);
  }
  return 0;
}

function fusionQuery(sql,fn,errfn) {
  //alert("fusionQuery: " + sql);
  var jsonpArgs = {
        url: "https://www.google.com/fusiontables/api/query",
        content: {sql:sql},  
        callbackParamName: "jsonCallback",
        load: function(data) {
            fn(data); return 0;},
        error: function(error) {
              if(errfn){errfn(error);}
        }
        };
   dojo.io.script.get(jsonpArgs);
}

function clearMap() {
   for (var m=0; m<markers.length; m++){
        markers[m].setMap(null);
   }
   markers = [];
   return 0;
}

function setup() {
   initialise();
   return 0;
}
</script>
</head>
<body class="tundra" style="background-color:white;margin:0px;padding:0px;">
<div class="container" > 
  <div style="background-color:black">
    <!--
    <img src="met_logo.gif" alt="Met Office logo" title="Met Office alpha"/><b>alpha</b>
    -->
    <h1>RFE map</h1>
    <p><a href="https://docs.google.com/document/pub?id=1CBaaZRCVDcGiuVuoM3XY14jNEXJO_QjlWv4n8KSGi5A">Help</a></p>
  </div>

<div  class="span-12">
<form  dojoType="dijit.form.Form" id="locationForm">
lat<input type="text" name="lat" class="short" dojoType="dijit.form.NumberTextBox" readonly />N
&nbsp;
lng<input type="text" name="lng" class="short" dojoType="dijit.form.NumberTextBox" readonly />E
<input type="text" name="alt" class="medium" dojoType="dijit.form.ValidationTextBox" readonly />
</form>
  <div id="map_canvas" style="width:460px;height:460px"></div>
</div>
<div  class="span-12 last" style="background-color:white">
<p>Rainfall estimate (mm)</p>
<div id="graphdivhi" style="width:455px;height:220px" ></div>
<p>Temperature (&deg;C)</p>
<div id="graphdivlo" style="width:455px;height:220px" ></div>
<form dojoType="dijit.form.Form" id="rainForm">
    <button type="button"  dojoType="dijit.form.Button" onClick="unzoom();">
    unzoom
    </button>
    <br>
    <input type="radio" dojoType="dijit.form.RadioButton" name="period" id="radioDekad"
    value="dekad" checked onchange="fetchData()"/>
    <label for="radioDekad">
        Dekad
    </label>
    <input type="radio" dojoType="dijit.form.RadioButton" name="period" id="radioMonth"
    value="month" onchange="fetchData()"/>
    <label for="radioMonth">
        Month
    </label>
    &nbsp;&nbsp;
    <label for="selectYear">Year</label>
    <div id="selectYear" style="width: 150px;" name="year" dojoType="dijit.form.Select"
     onchange="fetchData()">
      <span value="2006">
      2006
      </span>
      <span value="2007">
      2007
      </span>
      <span value="2008">
      2008
      </span>
      <span value="2009">
      2009
      </span>
      <span value="2010">
      2010
      </span>
    </div>
    <!--
    Month:
    <select name="month" dojoType="dijit.form.Select">
      <option value="01">Jan</option>
      <option value="02">Feb</option>
      <option value="03">Mar</option>
      <option value="04">Apr</option>
      <option value="05">May</option>
      <option value="06">Jun</option>
      <option value="07">Jul</option>
      <option value="08">Aug</option>
      <option value="09">Sep</option>
      <option value="10">Oct</option>
      <option value="11">Nov</option>
      <option value="12">Dec</option>
    </select>
    -->

</form>
</div>
<div  class="span-24 last" style="background-color:white">
<p>Caution:  Experimental system, data could be meaningless!</p>
<span id="info"></span>
</div>
</div> <!-- container -->
</body>
</html>
